
package server;

import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * server which listens for voting via the udp connection
 * 
 * The server is not finished. And absolutely not tested
 * @author radu
 */
public class UdpVoteServer extends Thread {

    static int MAX_DATA_SIZE = 1000;
    private DatagramPacket receivePacket;
    private DatagramSocket socket;
    private VoteListener voteList;

    public UdpVoteServer(int _listeningPort, VoteListener _voteList) {
        try {
            socket = new DatagramSocket(_listeningPort);
        } catch (SocketException se) {
            se.printStackTrace();
            System.exit(1);
        }
        this.voteList = _voteList;
    }

    @Override
    public void run() {
        // Construct a DatagramPacket for receiving packets
        byte data[] = new byte[MAX_DATA_SIZE];
        receivePacket = new DatagramPacket(data, data.length);

        VoteInterface vote ;
        
        for (;;) {
            try {
                socket.receive(receivePacket);
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(1);
            }
            
            try {
                vote = new UdpVote(receivePacket);
            } catch (Exception ex) {
                Logger logger = Logger.getLogger(UdpVoteServer.class.getName());
                logger.log(Level.WARNING, "UdpVoteServer: Invalid packet received");
                logger.log(Level.WARNING, null, ex);
                continue;
            }
            
            voteList.queueVote(vote);
        }
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        socket.close();
    }

}
